package com.yunhe.webmvc.servlet;

import com.yunhe.commons.util.ConfigUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author tianxuan
 * @version V1.0
 * @Date 2017/10/31 0031 上午 11:22
 * @Description:
 */
@WebServlet(name="Download", urlPatterns="/dl/img")
public class DownloadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String baseDir = ConfigUtils.readValue("fs.baseDir");   //  读取上传文件的根目录
        String fileName = req.getParameter("path");  //所要加载的图片名称
        File file = new File(baseDir + fileName);
        resp.setCharacterEncoding("utf-8");
//        String encodeFileName = URLEncoder.encode(fileName, "UTF-8"); //解决中文名称下载时 乱码问题
//        resp.setHeader("content-disposition","attachment;filename=" + encodeFileName); // 让浏览器以附件的形式下载文件，并指定文件名称
        if(file.exists()) {
            //.将要下载的文件读入内存
            InputStream fileInputStream = new FileInputStream(file);
            ServletOutputStream outputStream = resp.getOutputStream();  //获得输出流 进行下载
            byte[] buff = new byte[1024*1024];
            int len ;
            while ((len = fileInputStream.read(buff)) != -1){
                outputStream.write(buff,0,len);
            }
            outputStream.flush();
            outputStream.close();
        }

    }
}
